package com.huike.auth;

import com.huike.entity.Employee;
import com.huike.entity.Role;
import com.huike.mapper.EmployeeMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

//ctrl+h
@Component("authorizer")
public class MyRealm extends AuthorizingRealm {
    @PostConstruct
    public void setMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5");
        this.setCredentialsMatcher(matcher);
    }


    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //当前用户是什么角色，该角色有什么权限
        //1.当前用户怎么获取
        Employee user =(Employee) principalCollection.getPrimaryPrincipal();
        //2.获取该用户的所有角色，及对应的权限-->sql
        if (user.getAdmin()){
            info.addRole("admin");
            info.addStringPermission("*");
        }else{
            List<Role> roles = user.getRoles();
            //提取角色sn
            Set<String> collect = roles.stream().map(Role::getSn).collect(Collectors.toSet());
            if(!(collect.isEmpty())){
                info.addRoles(collect);
            }
            //加权限
            Set<String> permission = employeeMapper.getPermissionsByEmpId(user.getId());
            if(!permission.isEmpty()){
                info.addStringPermissions(permission);
            }
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        Employee dbUser = employeeMapper.getEmployeeByUsername((String) token.getPrincipal());
        //你塞得第一个参数就是主用户标识
        return new SimpleAuthenticationInfo(dbUser,dbUser.getPassword(),getName());
    }
}
